package com.pig4cloud.pig.djjk.service.immi;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.pig4cloud.pig.djjk.config.FaceApiConfig;
import com.pig4cloud.pig.djjk.domain.po.DetectionResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.logging.Logger;

import static com.pig4cloud.pig.djjk.utils.HttpUtil.postRequest;


/**
 * @className: FaceDetectService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2025/6/3
 **/
@Service
@Slf4j
public class FaceDetectService {
    @Autowired
	FaceApiConfig faceApiConfig;

    //获取人脸图片
    public String getFacePic(String base64Img) {

        try {
            // Read image file and encode as base6

            // Create JSON request
            JSONObject json = new JSONObject();

            json.put("image_base64", base64Img);

            // Create HTTP POST request
//            String responseString = null;
            String responseString = postRequest(faceApiConfig.getDetectUrl(), json.toString());
			log.info("请求人脸识别接口返回：{}",responseString);
            if (StringUtils.isNotEmpty(responseString)) {
                DetectionResponse detectionResponse = JSON.parseObject(
                        responseString,
                        new TypeReference<DetectionResponse>() {
                        }
                );
                if (CollectionUtil.isNotEmpty(detectionResponse.getFaces())) {
                    log.info("检测到人脸");
                    return detectionResponse.getFaces().get(0).getFace_base64();
                } else {
                    log.info("未检测到人脸");
                    return null;
                }
            }
            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
